<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <title>TestAPI</title>
</head>
<body>
    <input type="text" id="msg">
    <button id="submit">提交</button>
</body>
<script>
    // 创建 websocek 实例
    let websocket = new WebSocket("ws://127.0.0.1:8080/test");

    websocket.onopen = function () {
        console.log("WebSocket opened");
    }

    websocket.onmessage = function (event) {
        console.log("Received message", event.data);
    }

    websocket.onerror = function (event) {
        console.log("Received error", event);
    }

    // websocket.onclose(function () {
    //     console.log("WebSocket closed");
    // })
    //websocket.onclose(function() {...}) 是使用事件监听器的方式添加关闭事件处理函数，
    // 可以多次调用添加多个处理函数，它们会按添加顺序依次执行。

    //websocket.onclose = function() {...} 是直接赋值的方式，
    // 会覆盖之前设置的所有关闭事件处理函数，只能有一个处理函数生效
    websocket.onclose = function () {
        console.log("WebSocket closed");
    }

    let input = document.querySelector('#msg   ')
    let button = document.querySelector('#submit')
    button.onclick = function () {
        console.log("发送消息：" + input.value);
        websocket.send(input.value)
    }

</script>
</html>